package com.cyan.note.controller;

import com.cyan.note.dto.auth.LoginRequest;
import com.cyan.note.dto.auth.LoginResponse;
import com.cyan.note.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 * 处理用户登录、登出等认证相关请求
 * 
 * @author ZhangzhenYu
 * @since 2025-01-13
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {
    
    private final UserService userService;
    
    /**
     * 用户登录
     * 
     * @param loginRequest 登录请求
     * @return 登录响应
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@Valid @RequestBody LoginRequest loginRequest) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            LoginResponse loginResponse = userService.login(loginRequest);
            
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("data", loginResponse);
            
            log.info("用户 {} 登录成功", loginRequest.getUsername());
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            result.put("data", null);
            
            log.warn("用户 {} 登录失败: {}", loginRequest.getUsername(), e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
    
    /**
     * 用户登出
     * 
     * @return 登出响应
     */
    @PostMapping("/logout")
    public ResponseEntity<Map<String, Object>> logout() {
        Map<String, Object> result = new HashMap<>();
        
        // 由于使用JWT，客户端只需删除本地Token即可
        result.put("success", true);
        result.put("message", "登出成功");
        result.put("data", null);
        
        log.info("用户登出");
        return ResponseEntity.ok(result);
    }
    
    /**
     * 验证Token是否有效
     * 
     * @return 验证结果
     */
    @GetMapping("/validate")
    public ResponseEntity<Map<String, Object>> validateToken() {
        Map<String, Object> result = new HashMap<>();
        
        // 如果请求能到达这里，说明Token有效（通过了JWT过滤器）
        result.put("success", true);
        result.put("message", "Token有效");
        result.put("data", true);
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取当前登录用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("/userinfo")
    public ResponseEntity<Map<String, Object>> getCurrentUser() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从Security上下文中获取当前用户信息
            String username = com.cyan.note.util.SecurityUtils.getCurrentUsername();
            Long userId = com.cyan.note.util.SecurityUtils.getCurrentUserId();
            String role = com.cyan.note.util.SecurityUtils.getCurrentUserRole();
            Long shopId = com.cyan.note.util.SecurityUtils.getCurrentShopId();
            
            if (username == null) {
                result.put("success", false);
                result.put("message", "未找到当前用户信息");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 获取完整用户信息
            com.cyan.note.entity.User user = userService.findByUsername(username);
            if (user == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(result);
            }
            
            result.put("success", true);
            result.put("message", "获取用户信息成功");
            result.put("data", Map.of(
                "userId", userId,
                "username", username,
                "realName", user.getRealName(),
                "role", role,
                "roleName", userService.getRoleName(role),
                "shopId", shopId,
                "phone", user.getPhone(),
                "email", user.getEmail(),
                "status", user.getStatus()
            ));
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            result.put("success", false);
            result.put("message", "获取用户信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}